import { useState, useRef } from 'react';
import { Excalidraw, WelcomeScreen } from "@excalidraw/excalidraw";
// import cartu from '@/assets/libs/cartu.json';
import { addLibs, stringToUTF8ArrayBuffer, ApiType } from '@/utils/lib'
import Modal from '@/components/modal';
import { libs } from './utils';
import './index.css'

const width = 1080;

const Draw = ()=>{
    // const [excalidrawAPI, setExcalidrawAPI] = useState(null);
    const apiRef = useRef<ApiType>();
    const [isOpen, setIsOpen] = useState(false);

    const onApiRef = (api: any)=>apiRef.current = api;
    const openModal = () => {
        setIsOpen(true);
      };
    
      const closeModal = () => {
        setIsOpen(false);
      };

      const renderTopRightUI= () => {
        return (
          <button
            className="btn"
            onClick={openModal}
          >
            导入素材
          </button>
        );
      }
      const collectLibs = (lib:string)=>{
        const blob = new Blob([stringToUTF8ArrayBuffer(lib)])
        addLibs(apiRef.current as ApiType, blob);
        closeModal();
      }

    const renderLibs = libs.map(it=>(<div onClick={()=>collectLibs(it.data)} className="border p-4 text-center hover:scale-110 cursor-pointer h-64 overflow-hidden"><img className="w-full h-auto" src={it.img} /></div>))

    return (<>
        <div className="h-full">
          <Excalidraw renderTopRightUI={renderTopRightUI} excalidrawAPI={onApiRef} langCode="zh-CN" >
            <WelcomeScreen/>
          </Excalidraw>
        </div>
        <Modal width={width} isOpen={isOpen} onClose={closeModal}>
            <div style={{height: '500px'}} className="px-6 py-4 overflow-auto">
                <div className="grid grid-cols-3 gap-4">
                    {renderLibs}
                </div>
            </div>
        </Modal>
      </>)
}

export default Draw;
